/**
 * 证券选择组件
 * 用于在页面中提供证券搜索和选择功能
 * 
 * 使用示例:
 * var securitySelector = new SecuritySelector({
 *     inputId: 'securitySelect',
 *     dropdownId: 'securityDropdown',
 *     symbolInputId: 'securitySymbol',
 *     apiPrefix: ctx + 'security/',
 *     onSelect: function(security) {
 *         console.log('选中的证券:', security);
 *     }
 * });
 * securitySelector.init();
 */
function SecuritySelector(options) {
    this.options = $.extend({
        inputId: 'securitySelect',
        dropdownId: 'securityDropdown',
        symbolInputId: 'securitySymbol',
        apiPrefix: ctx + 'security/',
        onSelect: null,
        placeholder: '请输入名称或代码',
        width: '150px',
        enableHistory: false, // 是否启用搜索历史
        enableDeleteAll: true // 是否启用删除键一次性清空
    }, options || {});
    
    this.securitiesList = [];
    this.searchHistory = [];
    this.currentSelectedIndex = -1;
    this.namespace = 'securitySelector_' + Math.random().toString(36).substr(2, 9);
}

SecuritySelector.prototype = {
    /**
     * 初始化组件
     */
    init: function() {
        var self = this;
        
        // 加载证券列表
        this.loadSecuritiesList();
        
        // 绑定搜索框事件
        this.bindEvents();
    },
    
    /**
     * 加载证券列表
     */
    loadSecuritiesList: function() {
        var self = this;
        $.ajax({
            url: this.options.apiPrefix + 'securities',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                if (data.code === 0 && data.data) {
                    self.securitiesList = data.data;
                }
            },
            error: function(xhr, status, error) {
                console.error('获取证券列表失败:', error);
            }
        });
    },
    
    /**
     * 绑定事件
     */
    bindEvents: function() {
        var self = this;
        var input = $('#' + this.options.inputId);
        var namespace = '.' + this.namespace;
        
        // 输入事件
        input.off('input' + namespace);
        input.on('input' + namespace, function() {
            var searchText = $(this).val().toLowerCase();
            if (searchText.includes(' - ')) {
                var parts = searchText.split(' - ');
                if (parts.length > 1) {
                    searchText = parts[parts.length - 1].toLowerCase();
                }
            }
            if (searchText.length > 0) {
                self.showDropdown(searchText);
            } else {
                self.hideDropdown();
            }
        });
        
        // 键盘事件处理
        input.off('keydown' + namespace);
        input.on('keydown' + namespace, function(e) {
            var dropdown = $('#' + self.options.dropdownId);
            var items = dropdown.find('.dropdown-item');
            
            // 处理删除键（Backspace 或 Delete），一次性清空所有文字
            if (self.options.enableDeleteAll && (e.keyCode === 8 || e.keyCode === 46)) {
                var currentValue = $(this).val();
                if (currentValue && currentValue.length > 0) {
                    e.preventDefault();
                    $(this).val('');
                    $('#' + self.options.symbolInputId).val('');
                    self.hideDropdown();
                    self.currentSelectedIndex = -1;
                    if (self.options.onClear) {
                        self.options.onClear();
                    }
                    return;
                }
            }
            
            if (items.length === 0) {
                return;
            }
            
            switch(e.keyCode) {
                case 38: // 上箭头
                    e.preventDefault();
                    self.currentSelectedIndex = Math.max(0, self.currentSelectedIndex - 1);
                    self.updateSelection(items);
                    break;
                case 40: // 下箭头
                    e.preventDefault();
                    self.currentSelectedIndex = Math.min(items.length - 1, self.currentSelectedIndex + 1);
                    self.updateSelection(items);
                    break;
                case 13: // 回车
                    e.preventDefault();
                    if (self.currentSelectedIndex >= 0 && self.currentSelectedIndex < items.length) {
                        items.eq(self.currentSelectedIndex).click();
                    }
                    break;
                case 27: // ESC
                    e.preventDefault();
                    self.hideDropdown();
                    self.currentSelectedIndex = -1;
                    break;
            }
        });
        
        // 点击其他地方隐藏下拉框
        $(document).off('click' + namespace);
        $(document).on('click' + namespace, function(e) {
            if (!$(e.target).closest('#' + self.options.inputId + ', #' + self.options.dropdownId).length) {
                self.hideDropdown();
            }
        });
        
        // 鼠标悬停显示历史记录（如果启用）
        if (this.options.enableHistory) {
            input.off('mouseenter' + namespace);
            input.on('mouseenter' + namespace, function() {
                if (self.searchHistory.length > 0) {
                    self.showSearchHistory();
                }
            });
            
            input.off('mouseleave' + namespace);
            input.on('mouseleave' + namespace, function() {
                setTimeout(function() {
                    if (!$('#' + self.options.dropdownId + ':hover').length && !input.is(':hover')) {
                        self.hideDropdown();
                    }
                }, 200);
            });
        }
    },
    
    /**
     * 显示下拉框
     */
    showDropdown: function(searchText) {
        var self = this;
        var dropdown = $('#' + this.options.dropdownId);
        dropdown.empty();
        
        var filteredSecurities = this.securitiesList.filter(function(security) {
            var code = (security.code || '').toLowerCase();
            var name = (security.name || '').toLowerCase();
            var fullCode = (security.exchange + security.code).toLowerCase();
            var search = searchText.toLowerCase();
            return code.includes(search) || name.includes(search) || fullCode.includes(search);
        });
        
        if (filteredSecurities.length > 0) {
            filteredSecurities.forEach(function(security) {
                var displayCode = security.exchange + security.code;
                var displayText = displayCode + ' - ' + security.name;
                
                var item = $('<div class="dropdown-item">' +
                    '<strong>' + displayCode + '</strong> - ' + security.name + '</div>');
                
                item.hover(
                    function() { $(this).css('background-color', '#f5f5f5'); },
                    function() { $(this).css('background-color', 'white'); }
                );
                
                item.on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $('#' + self.options.inputId).val(displayText);
                    $('#' + self.options.symbolInputId).val(displayCode);
                    self.hideDropdown();
                    
                    // 添加到搜索历史（如果启用）
                    if (self.options.enableHistory) {
                        self.addToSearchHistory(security);
                    }
                    
                    // 触发选择回调
                    if (self.options.onSelect) {
                        self.options.onSelect(security);
                    }
                    
                    return false;
                });
                
                dropdown.append(item);
            });
            dropdown.show();
        } else {
            dropdown.hide();
        }
    },
    
    /**
     * 隐藏下拉框
     */
    hideDropdown: function() {
        $('#' + this.options.dropdownId).hide();
        this.currentSelectedIndex = -1;
    },
    
    /**
     * 更新选中项的高亮显示
     */
    updateSelection: function(items) {
        items.removeClass('selected');
        if (this.currentSelectedIndex >= 0 && this.currentSelectedIndex < items.length) {
            items.eq(this.currentSelectedIndex).addClass('selected');
        }
    },
    
    /**
     * 显示搜索历史（如果启用）
     */
    showSearchHistory: function() {
        var self = this;
        var dropdown = $('#' + this.options.dropdownId);
        dropdown.empty();
        
        var recentHistory = this.searchHistory.slice(-10).reverse();
        
        if (recentHistory.length > 0) {
            var titleItem = $('<div style="padding: 8px 12px; background-color: #f5f5f5; border-bottom: 1px solid #ddd; font-size: 12px; color: #666; font-weight: bold;">最近搜索</div>');
            dropdown.append(titleItem);
            
            recentHistory.forEach(function(historyItem) {
                var item = $('<div class="dropdown-item" style="padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;">' +
                    '<span><strong>' + historyItem.code + '</strong> - ' + historyItem.name + '</span>' +
                    '<span style="font-size: 11px; color: #999;">' + historyItem.time + '</span>' +
                    '</div>');
                
                item.hover(
                    function() { $(this).css('background-color', '#f5f5f5'); },
                    function() { $(this).css('background-color', 'white'); }
                );
                
                item.on('click', function(e) {
                    e.stopPropagation();
                    $('#' + self.options.inputId).val(historyItem.code + ' - ' + historyItem.name);
                    $('#' + self.options.symbolInputId).val(historyItem.code);
                    self.hideDropdown();
                    
                    // 查找对应的证券对象
                    var security = self.securitiesList.find(function(s) {
                        return (s.exchange + s.code) === historyItem.code;
                    });
                    
                    if (self.options.onSelect && security) {
                        self.options.onSelect(security);
                    }
                });
                
                dropdown.append(item);
            });
            
            var clearItem = $('<div style="padding: 8px 12px; text-align: center; color: #999; font-size: 12px; cursor: pointer; border-top: 1px solid #eee;">清空历史记录</div>');
            clearItem.on('click', function(e) {
                e.stopPropagation();
                self.clearSearchHistory();
            });
            dropdown.append(clearItem);
            
            dropdown.show();
        }
    },
    
    /**
     * 添加到搜索历史
     */
    addToSearchHistory: function(security) {
        var historyItem = {
            code: security.exchange + security.code,
            name: security.name,
            time: new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'})
        };
        
        var exists = this.searchHistory.some(function(item) {
            return item.code === historyItem.code;
        });
        
        if (!exists) {
            this.searchHistory.push(historyItem);
            if (this.searchHistory.length > 20) {
                this.searchHistory = this.searchHistory.slice(-20);
            }
        }
    },
    
    /**
     * 清空搜索历史
     */
    clearSearchHistory: function() {
        this.searchHistory = [];
        this.hideDropdown();
    },
    
    /**
     * 获取选中的证券
     */
    getSelectedSecurity: function() {
        var inputValue = $('#' + this.options.inputId).val();
        if (!inputValue || !inputValue.includes(' - ')) {
            return null;
        }
        
        var codeWithPrefix = inputValue.split(' - ')[0];
        return this.securitiesList.find(function(security) {
            return (security.exchange + security.code) === codeWithPrefix;
        });
    },
    
    /**
     * 设置选中的证券
     */
    setSelectedSecurity: function(security) {
        if (!security) return;
        
        var displayCode = security.exchange + security.code;
        var displayText = displayCode + ' - ' + security.name;
        
        $('#' + this.options.inputId).val(displayText);
        $('#' + this.options.symbolInputId).val(displayCode);
        
        if (this.options.onSelect) {
            this.options.onSelect(security);
        }
    },
    
    /**
     * 销毁组件
     */
    destroy: function() {
        var namespace = '.' + this.namespace;
        $('#' + this.options.inputId).off(namespace);
        $(document).off('click' + namespace);
        this.hideDropdown();
    }
};

